package com.xgr.wonderful.activity;


import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.base.BasePageActivity;
import com.xgr.wonderful.adapter.PersonalCenterAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LocationUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
/**
 * my center
 * @author lsj
 *
 */
public class PersonalCenterActivity  extends BasePageActivity{
	
	private ArrayList<Status> mStatusList = new ArrayList<Status>() ;
	private PersonalCenterAdapter mAdapter ;
	private PullToRefreshListView mPullRefreshListView ;
	private ListView actualListView ;
	
	private TextView mNetworkTips ;
	private ProgressBar mProgressBar ;
	private ActionBar mActionBar ;
	
	private  enum RefreshType {
		REFRESH , LOAD_MORE 
	};
	
	private RefreshType mRefreshType = RefreshType.REFRESH ;
	
	private Integer lastStatusId = 0;
	private User mUser ;
	private HttpProxy httpProxy ;
	private int clickIndex =-1 ;
	
	@Override
	protected void setLayoutView() {
		setContentView(R.layout.activity_personal_center) ;
	}

	@Override
	protected void findViews() {
		mActionBar = (ActionBar)findViewById(R.id.actionbar_personal) ;
		mPullRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_list) ;
		mNetworkTips = (TextView)findViewById(R.id.networkTips) ;
		mProgressBar = (ProgressBar)findViewById(R.id.progressBar) ;
	}

	@Override
	protected void setupViews(Bundle bundle) {
		mActionBar.setTitle("个人中心") ;
		mActionBar.setDisplayHomeAsUpEnabled(true) ;
		mActionBar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				finish() ;
			}
			
			@Override
			public int getDrawable() {
				// TODO Auto-generated method stub
				return R.drawable.weix_logo_blank;
			}
		}) ;
		
		httpProxy = new HttpProxy() ;
		mPullRefreshListView.setMode(Mode.BOTH);
		// 设置上下拉时的显示文字 ,还可以设置图片
		ILoadingLayout startLabels = mPullRefreshListView
				.getLoadingLayoutProxy(true, false);
		startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
		startLabels.setRefreshingLabel("正在载入...");// 刷新时
		startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

		ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
				false, true);
		endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("正在载入...");// 刷新时
		endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示
		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener2<ListView>() {
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.REFRESH;
						fetchData();
					}

					@Override
					// 上拉事件
					public void onPullUpToRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mPullRefreshListView.setMode(Mode.BOTH);
						mRefreshType = RefreshType.LOAD_MORE;
						fetchData();
					}
				});
		mUser = (User)getIntent().getSerializableExtra("data"); 
		if (mUser == null){
			mUser = LocalUserUtils.getInstance().getLocalUser() ;
		}
		actualListView = mPullRefreshListView.getRefreshableView() ;
		mAdapter = new PersonalCenterAdapter(mContext, mStatusList , mUser) ; // not ok
		actualListView.setAdapter(mAdapter) ;
		
		if (mStatusList== null || mStatusList.size()==0){
			fetchData() ;
		}
		
		// 进入评论页面
		actualListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 1) return ;
				clickIndex = position -2 ;
				Intent intent = new Intent();
				intent.setClass(mContext, CommentActivity.class);
				intent.putExtra("data", mStatusList.get(clickIndex));
				startActivityForResult(intent,
						Constant.REQUEST_CODE_COMMENT_NUM);
			}
		});
	}
	
	public void fetchData() {
		Status status = null;
		String statusJson = null;
		Double lat = LocationUtils.getInstance().getLatitude();
		Double lng = LocationUtils.getInstance().getLongtitude();
		if (mRefreshType == RefreshType.REFRESH){
			status = new Status(mUser.getID(), 0, 
					Constant.NUMBERS_PER_PAGE, null, lat, lng);
		}else {
			status = new Status(mUser.getID(), lastStatusId, 
					Constant.NUMBERS_PER_PAGE, null, lat, lng);
		}
		try {
			statusJson = new Gson().toJson(status);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (statusJson != null) {
			httpProxy.queryStatus(statusJson, new IHttpRequestListener() {

				@Override
				public void OnHttpRequestSuccessful(String result, int errCode) {
					handleData(result, errCode);
				}

				@Override
				public void OnHttpRequestStart() {
					setState(LOADING);
				}

				@Override
				public void OnHttpRequestFailure(String info) {
					ToastFactory.getToast(mContext, "更新数据失败，请检查网络环境后重试").show();
					setState(LOADING_FAILED);
					mPullRefreshListView.onRefreshComplete();
				}
			});
		}
	}
	
	private void handleData(String result, int errCode) {
		List<Status> queryList = null;
		if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS) {
			try {
				queryList = new Gson().fromJson(result,
						new TypeToken<List<Status>>() {
						}.getType());
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (queryList != null && queryList.size() != 0) {
				if (mRefreshType == RefreshType.REFRESH) {
					mStatusList.clear();
				}
				if (queryList.size() < Constant.NUMBERS_PER_PAGE) {
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				}
				mStatusList.addAll(queryList);
				lastStatusId = mStatusList.get(mStatusList.size() - 1).getId();
				mAdapter.notifyDataSetChanged();
			} else if (queryList != null && queryList.size() == 0) {
				if (lastStatusId > 0) {
					// 说明 有status且不是第一次拉取，然后没有数据了
					ToastFactory.getToast(mContext, "没有更多数据了").show();
				} else {
					// 本来就没有评论，所以为0， 不用显示
					ToastFactory.getToast(mContext, "暂时还没有数据").show();
				}
			}
			setState(LOADING_COMPLETED);
			mPullRefreshListView.onRefreshComplete();
		} else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
			ToastFactory.getToast(mContext, "加载数据失败").show();
			setState(LOADING_FAILED);
			mPullRefreshListView.onRefreshComplete();
		}
	}
	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		
	}
	
	private static final int LOADING = 1;
	private static final int LOADING_COMPLETED = 2;
	private static final int LOADING_FAILED = 3;
	private static final int LOADING_NO_MORE_DATA = 4;

	public void setState(int state) {
		switch (state) {
		case LOADING: // 正在定位中或者数据正在拉取中
			if (mStatusList == null || mStatusList.size() == 0) {
				mNetworkTips.setVisibility(View.GONE);
				mProgressBar.setVisibility(View.VISIBLE);
			}
			break;
		case LOADING_COMPLETED:
			mNetworkTips.setVisibility(View.GONE);
			mProgressBar.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			break;
		case LOADING_FAILED:
			if (mStatusList == null || mStatusList.size() == 0) {
				mNetworkTips.setVisibility(View.VISIBLE);
			}
			mPullRefreshListView.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.GONE);
			break;
		case LOADING_NO_MORE_DATA:
			mNetworkTips.setVisibility(View.GONE);
			mPullRefreshListView.setVisibility(View.VISIBLE);
			mProgressBar.setVisibility(View.GONE);
		default:
			break;
		}
	}
	
	@Override
	protected void onDestroy() {
		//暂时不用这个，没有必要 
//		if (mUser.getID() == LocalUserUtils.getInstance().getLocalUserID()) {
//			Cache.putUserPublishedStatus(new Gson().toJson(mStatusList));
//		}
		super.onDestroy();
	}


}
